package com.gzyj.flink.driver.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class RedisSessionFactory {
    private static LettuceConnectionFactory factory;

    private RedisSessionFactory() {
        super();
    }

    public synchronized static LettuceConnectionFactory getRedisFactory() {
        if (factory == null) {
            String host = "127.0.0.1";

            RedisClusterConfiguration server = new RedisClusterConfiguration();
            List<RedisNode> nodes = new ArrayList<>();
            RedisNode redisNode7001 = new RedisNode(host, 7001);
            nodes.add(redisNode7001);
            RedisNode redisNode7002 = new RedisNode(host, 7002);
            nodes.add(redisNode7002);
            RedisNode redisNode7003 = new RedisNode(host, 7003);
            nodes.add(redisNode7003);

            RedisNode redisNode8001 = new RedisNode(host, 8001);
            nodes.add(redisNode8001);
            RedisNode redisNode8002 = new RedisNode(host, 8002);
            nodes.add(redisNode8002);
            RedisNode redisNode8003 = new RedisNode(host, 8003);
            nodes.add(redisNode8003);

            server.setClusterNodes(nodes);

            GenericObjectPoolConfig genericObjectPoolConfig =
                    new GenericObjectPoolConfig();
            genericObjectPoolConfig.setMaxIdle(4);
            genericObjectPoolConfig.setMinIdle(0);
            genericObjectPoolConfig.setMaxTotal(8);
            genericObjectPoolConfig.setMaxWaitMillis(10000);

            //redis客户端配置
            LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                    builder = LettucePoolingClientConfiguration.builder().
                    commandTimeout(Duration.ofMillis(10 * 1000));

            builder.shutdownTimeout(Duration.ofMillis(4000));
            builder.poolConfig(genericObjectPoolConfig);
            LettuceClientConfiguration lettuceClientConfiguration = builder.build();

            factory = new LettuceConnectionFactory(server, lettuceClientConfiguration);
            factory.afterPropertiesSet(); //刷新配置
        }


        return factory;
    }
}
